package com.itlong.cloud.controller.sdkV2.serverClient;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.sdk.SDKOffLineDeveloperDTO;
import com.itlong.cloud.POJO.PO.ProjectPO;
import com.itlong.cloud.POJO.PO.PropertyRoleProjectPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.sdk.SDKServerUserCacheVO;
import com.itlong.cloud.enumerate.PropertyPublicRoleEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.SDKErrorCodeEnum;
import com.itlong.cloud.project.sdk.ISDKServerOldProjectServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.sdk.ISDKServerOldUserServiceClient;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <desc>
 *      新离线版SDK项目地址Controller
 * </desc>
 *
 * @createDate 2017/12/12
 */
@RestController
@RequestMapping("/sdk/projectManage")
public class SDKOfflineProjectController {

    @Autowired
    ISDKServerOldUserServiceClient iSDKServerUserServiceClient;

    @Autowired
    ISDKServerOldProjectServiceClient iSDKProjectServiceClient;

    private static Logger LOG = LoggerFactory.getLogger(SDKOfflineProjectController.class);

    /**
     * <desc>
     *      向家半径云服务器获取项目信息，包括项目ID、项目公钥等
     * <desc/>
     * @param   developerDTO   离线版SDK开发者账号请求DTO
     * @return  标准化响应结果
     * @author Biao.R
     * @createDate 2017/12/12
     */
    @ResponseBody
    @RequestMapping("getAppInfos")
    public MessageVO getAppInfos(SDKOffLineDeveloperDTO developerDTO) {
        try {
            LOG.info("===向家半径云服务器获取项目信息getAppInfos: developerDTO:"+String.valueOf(developerDTO));
            String appid = developerDTO.getAppid();
            String appsecret = developerDTO.getAppsecret();

            String projectId = developerDTO.getProjectId();
            //开发者账号和密钥非空校验
            if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(appsecret)) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_IS_NULL.getErrorCode());
            }

            SDKServerUserCacheVO serverCacheVO = iSDKServerUserServiceClient.sdkServerLogin(appid, appsecret);
            if (serverCacheVO == null) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_ERR.getErrorCode());
            }
            JSONArray projectArr = new JSONArray();
            //查询该独立开发者的项目信息
            PropertyRoleProjectPO roleProjectPO = new PropertyRoleProjectPO(projectId, PropertyPublicRoleEnum.DEVELOPER.getRoleId(), appid);
            List<ProjectPO> projectPOS = iSDKProjectServiceClient.getDeveloperProjects(roleProjectPO);
            if (projectPOS != null && !projectPOS.isEmpty()) {
                for (ProjectPO projectPO : projectPOS) {
                    String getProjectId = projectPO.getProjectId();
                    String pubKey = projectPO.getPubKey();
                    JSONObject js = new JSONObject();
                    js.put("projectId", getProjectId);
                    js.put("remark", projectPO.getProjectMemo());
                    //对pubKey进行对称加密
                    js.put("encryptedKey", DesEncryptUtil.encode(getProjectId, pubKey));
                    projectArr.add(js);
                }
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), projectArr);
        } catch (Exception e) {
            throw new DataAccessException("【SDK_服务端_项目getAppInfos】获取SDK项目的项目信息异常", e);
        }
    }


    /**
     * <desc>
     *      向家半径云服务器获取项目信息，包括项目ID、项目公钥等
     * <desc/>
     * @param   developerDTO   离线版SDK开发者账号请求DTO
     * @return  标准化响应结果
     * @author Biao.R
     * @createDate 2017/12/12
     */
    @ResponseBody
    @RequestMapping("getKeyU")
    public MessageVO getKeyU(SDKOffLineDeveloperDTO developerDTO) {
        try {
            LOG.info("===向家半径云服务器获取项目信息getAppInfos: developerDTO:" + String.valueOf(developerDTO));

            String appid = developerDTO.getAppid();
            String appsecret = developerDTO.getAppsecret();
            String projectId = developerDTO.getProjectId();
            String encryptedKey = developerDTO.getEncryptedKey();
            String userId = developerDTO.getUserId();
            //开发者账号和密钥非空校验
            if (StringUtils.isEmpty(appid) || StringUtils.isEmpty(appsecret)) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_IS_NULL.getErrorCode());
            }

            SDKServerUserCacheVO serverCacheVO = iSDKServerUserServiceClient.sdkServerLogin(appid, appsecret);
            if (serverCacheVO == null) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_DEVELOP_ERR.getErrorCode());
            }

            if (StringUtils.isEmpty(encryptedKey) || StringUtils.isEmpty(projectId) || !userId.matches("[A-Fa-f0-9]+")) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_ENPUBKEY_USERID_IS_ILLEGAL.getErrorCode());
            }
            userId = userId.toUpperCase();
            //如果userId长度大于8位后,获得16位MD5加密值，取奇数位拼接成字符串
            if (userId.length() > 8) {
                userId = Md5EncryptUtil.offLineUserIdHandler(userId);
            }
            String pubKey = DesEncryptUtil.decode(projectId, encryptedKey);
            String keyU = DesEncryptUtil.encode(pubKey, userId);
            JSONObject js = new JSONObject();
            js.put("keyU", keyU);

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), js);
        } catch (Exception e) {
            throw new DataAccessException("【SDK_服务端_项目getAppInfos】离线版SDK用户注册异常", e);
        }
    }


}